package com.codingx.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class JsonUtil {
    private static ObjectMapper om = new ObjectMapper();

    static {
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 序列化对象
     *
     * @param obj
     * @return
     */
    public static String serializeValue(Object obj) {
        try {

            return om.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("序列化异常", e);
        }
        return null;
    }

    /**
     * 反序列化对象
     *
     * @param jsonStr
     * @param calssz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String jsonStr, Class<T> calssz) {
        try {
            return om.readValue(jsonStr, calssz);

        } catch (JsonProcessingException e) {
            log.error("Json转换异常", e);
        }
        return null;
    }

    /**
     * 反序列化对象
     *
     * @param objValue
     * @param calssz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(Object objValue, Class<T> calssz) {
        try {
            return om.readValue(om.writeValueAsString(objValue), calssz);
        } catch (JsonProcessingException e) {
            log.error("Json转换异常", e);
        }
        return null;
    }

    public static <T> T deserialize(InputStream inputStream, Class<T> calssz) {
        try {
            return om.readValue(inputStream, calssz);
        } catch (IOException e) {
            log.error("Json转换异常", e);
        }
        return null;
    }
}
